'''
Created on Oct 13, 2012

@author: raygomez
'''

from Unsigned32AVP import Unsigned32AVP
from Error import InvalidAVPLengthError
from struct import unpack
from datetime import datetime

class TimeAVP(Unsigned32AVP):
    """A timestamp AVP.
    TimeAVP contains a second count since 1900.
    """
    
    secsFrom1900to1970 = ((70 * 365) + 17) * 86400
    
    def __init__(self, code, secSince1970, vendorId=0):
        Unsigned32AVP.__init__(self, code,
                               secSince1970 + TimeAVP.secsFrom1900to1970,
                               vendorId)
        
    def getValue(self):
        return Unsigned32AVP.getValue(self) - TimeAVP.secsFrom1900to1970
    
    def setValue(self, secsSince1970):
        return Unsigned32AVP.setValue(self,
                                      secsSince1970 + TimeAVP.secsFrom1900to1970)
    
    @staticmethod
    def convert(avp):
        """Convert generic AVP to Unsigned32
        Raises: InvalidAVPLengthError
        """
        if len(avp.payload) != 4:
            raise InvalidAVPLengthError(avp)
        value = unpack("!I", avp.payload[0] - TimeAVP.secsFrom1900to1970)
        a = TimeAVP(avp.code, value, avp.vendorId)
        a.flags = avp.flags
        return a
    
    def __str__(self):
        return str(self.code) + ":" + str(datetime.fromtimestamp(self.getValue()))
